package com.example.shopping.service.login;


import com.example.shopping.entity.Admin;
import com.example.shopping.entity.User;
import com.example.shopping.mapper.UserMapper;
import com.example.shopping.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;

@Component
public class PasswordStrategy implements LoginStrategy {

    @Autowired
    private AdminService adminService;
    @Autowired
    private UserMapper userMapper;

    //冻结时间，以秒为单位
    public static long freezeTime = 60;

    @Override
    public User login(Object... credentials) {
        //如果参数数量不等于2就返回null
        if (credentials.length != 2) {
            return null;
        }
        String account = (String) credentials[0];
        String password = (String) credentials[1];
        //业务逻辑
        //判断是否是管理员登录
        if ("admin".equals(account)) {
            Admin admin = adminService.login(account, password);
            if (admin != null) {
                User u = new User();
                u.setId(admin.getId());
                u.setAccount(account);
                u.setPassword(DigestUtils.md5DigestAsHex(password.getBytes()));
                u.setStatus("1");
                return u;
            }
            return null;
        }
        //1. 拿到正确的用户
        User cur = userMapper.getUserByAccount(account);
        if (cur == null) {
            return null;//没有该用户
        }
        if (!cur.getPassword().equals(DigestUtils.md5DigestAsHex(password.getBytes()))) {
            return null;//密码错误
        }
        //判断用户是否被冻结
        if (cur.getStatus().equals("2")) {
            //是否可以解冻了，判断时间
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime oldLoginTime = cur.getLastLoginTime();
            // 如果当前时间大于上次登录时间加上冻结时间，则解冻
            if (oldLoginTime.plusSeconds(freezeTime).isAfter(now)) {
                //还在冻结期
                return null;
            }
        }
        /*-------判断用户是否是黑名单-------*/
        if (cur.getStatus().equals("3")) {
            return null;
        }
        //正常登录或已经可以解冻
        //修改用户的登录时间
        cur.setLastLoginTime(LocalDateTime.now());
        cur.setStatus("1");//已经登录
        //更新用户信息
        int re = userMapper.updateUserStatus(cur.getId(), cur.getStatus());
        return cur;

    }

    @Override
    public String getLoginType() {
        return "password";
    }
}
